#!/bin/bash
#author:xu3352@gmail.com
#desc: rotate tomcat catalina.out daily

do_job() {
  local DATE=$(date "+%Y%m%d")
  # tomcat base dir list
  local TOMCAT_BASES=($(ps aux | grep -v grep | grep "tomcat" | awk '{for(i=1;i<=NF;i++){if ($i ~ /catalina.base/){printf("%s\n", $i)}}}' | awk -F '=' '{print $2}'))

  local LEN=${#TOMCAT_BASES[*]}
  # echo "LEN:" $LEN

  for ((i = 0; i < $LEN; i++)); do
    echo "Tomcat Base Dir : ${TOMCAT_BASES[i]}"
    backup "${TOMCAT_BASES[i]}"
    clean_expired "${TOMCAT_BASES[i]}"
    echo "backup and clean success ^_^ "
  done
}

backup() {
  cd $1/logs/
  if [ ! -f "catalina.out.$DATE" ]; then
    echo "backup to catalina.out.$DATE if not exists..."
    # copy
    cp catalina.out catalina.out.$DATE
    # truncate
    echo "" >catalina.out
  fi
}

clean_expired() {
  echo "clean expired 7 days catalina.out log..."
  find $1/logs/ -name "catalina.out.*" -type f -mtime +7 | xargs rm -rf
  find $1/logs/ -name "*.log" -type f -mtime +15 | xargs rm -rf
}

# start job
do_job